﻿using ERPSystem.Common.Domains.Department;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using SqlSugar;

namespace BasicInformationCommon.API.BasicInformationCommons.DepartmentTrees
{
    public class DepartmentQueryHandler:IRequestHandler<DepartmentQueryCommand,Result<PageResultDto<DepartmentDto>>>
    {
        private readonly ISqlSugarClient db;

        public DepartmentQueryHandler(ISqlSugarClient db)
        {
            this.db = db;
        }


        /// <summary>
        /// 部门显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<DepartmentDto>>> Handle(DepartmentQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<DepartmentDto>>();
            var page = new PageResultDto<DepartmentDto>() { TotalCount=0,TotalPage=0,List=new List<DepartmentDto>{ }};
            try
            {
                RefAsync<int> totalCount = 0;
                RefAsync<int> totalPage = 0;
                var list = db.Queryable<DepartmentTree,Depart>((a, b) => a.DepartmentTreeId == b.DepartmentTreeId).Where(a=>a.DepartmentTreeId==request.DepartmentTreeId).Select((a, b) => new DepartmentDto()
                {
                    DepartmentTreeId = b.DepartmentTreeId,
                    DepartmentDeactivatebool = b.DepartmentDeactivatebool,
                    DepartmentType = b.DepartmentType,
                    DepartAddress = b.DepartAddress,
                    DirectSuperior = b.DirectSuperior,
                    DepartmentSupervisor = b.DepartmentSupervisor,
                    InChargeHead = b.InChargeHead,
                    Treasurer = b.Treasurer,
                    ViewablePersonnel = b.ViewablePersonnel,
                    DepartmentTreeName = a.DepartmentTreeName,
                    Pid = a.Pid
                });
                //if(request.DepartmentTreeId !=0)
                //{
                //    list = list.Where(x => x.DepartmentTreeId == request.DepartmentTreeId);
                //}
                var res = await list.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                page.TotalCount = totalCount;
                page.TotalPage = totalPage;
                page.List = res;
                if(page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取部门信息成功";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
